//
//  XMCameraTimeAndAngleViewController.m
//  XiaoMiao
//
//  Created by Jim huang on 2018/4/21.
//  Copyright © 2018年 smallyou. All rights reserved.
//


//controller
#import "XMCameraTimeAndAngleViewController.h"
#import "XMTypeListViewController.h"

//view
#import "XMCameraTimeTableViewCell.h"
#import "XMCameraAngleTableViewCell.h"
#import "XMTitleAlterView.h"

//model
#import "XMUserCreateModel.h"
#import "KV2CameraAngleNormalModel.h"

//request


@interface XMCameraTimeAndAngleViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView * tableView;
//下一步
@property (nonatomic,strong) UIButton * nextBtn;

@property (nonatomic,strong) NSMutableArray * list;
//数据model
@property (nonatomic,strong) KV2CameraAngleNormalModel * normalModel;
//一级分类
@property (nonatomic,strong) KV2GetCameraAngleCateModel * cateModel;
//二级分类
@property (nonatomic,strong) KV2GetCameraAngleCateModel * cateSubModel;
//新建用户
@property (nonatomic,strong) XMUserCreateModel * createModel;

@end

@implementation XMCameraTimeAndAngleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    self.title = @"拍摄角度选择";
    [self getNormalList];
    self.createModel = [[XMUserCreateModel alloc]init];
    
    
}

-(void)setUI{
    
    self.tableView.showsVerticalScrollIndicator = NO;

    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.nextBtn.mas_top);
    }];
    
}


#pragma mark ----netWork
-(void)getNormalList{
    
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_V2GetCameraAngleNormalWithrealName:self.partyId completion:^(BOOL success, KV2CameraAngleNormalModel *model, AppError *error) {
        
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            //设置默认选第一个
            if (model.cateViews.count>0) {
                KV2GetCameraAngleCateModel * cateModel = model.cateViews[0];
                weakSelf.cateModel = cateModel;
                cateModel.isSelected = YES;
            }

            if (model.cateViewsSub.count>0) {
                KV2GetCameraAngleCateModel * cateSubmodel = model.cateViewsSub[0];
                weakSelf.cateSubModel = cateSubmodel;
                cateSubmodel.isSelected = YES;

            }
            
            weakSelf.normalModel = model;
            KV2CameraAngleModel * newModel = [[KV2CameraAngleModel alloc]init];
            newModel.name = @"自定义";
            [weakSelf.normalModel.photoAngleTemplateViews addObject:newModel];
            
            [weakSelf.tableView reloadData];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
        
    }];
}

-(void)getAngleList{
    
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    
    [AppNetwork album_V2GetCameraAngleWithRealName:self.partyId cateId:self.cateModel.id subCateId:self.cateSubModel.id completion:^(BOOL success, NSMutableArray<KV2CameraAngleModel *> *models, AppError *error) {
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            
            weakSelf.normalModel.photoAngleTemplateViews = models;

            KV2CameraAngleModel * newModel = [[KV2CameraAngleModel alloc]init];
            newModel.name = @"自定义";
            [weakSelf.normalModel.photoAngleTemplateViews addObject:newModel];
            [weakSelf.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
            
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
}


-(void)checkImage{
    if (!self.cateModel || !self.cateSubModel) {
        [KLProgressHUD showErrorHUDWithMessage:@"请选择分类"];
        return;
    }

    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
    XMCameraAngleTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    
    NSMutableArray * cellListData = cell.data;
    
    BOOL showAlter = NO;
    BOOL isPhoto = NO;
    for (KV2CameraAngleModel * model in cellListData) {
        if ((model.normalImageUrl.length == 0 && model.normalImage == nil) && ![model.name containsString:@"自定义"]) {
            showAlter = YES;
            
        }
        
       if (model.normalImageUrl.length != 0 || model.normalImage != nil){
           isPhoto = YES;
        }
    }

    if (!isPhoto) {
        [KLProgressHUD showErrorHUDWithMessage:@"至少拍摄一张照片"];
        return;
    }
    
    if (showAlter){
        MJWeakSelf
        [XMTitleAlterView showTypeMaterialListWithTitle:@"图片有缺失,是否进行下一步" sureBlock:^{
            [weakSelf uploadImageRequest];
        } cancelBlock:^{
            
        }];
    }else{
        [self uploadImageRequest];
    }
    
}

//上传照片获取路径
- (void)uploadImageRequest
{
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
    XMCameraAngleTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    NSMutableArray * cellListData = cell.data;
    
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"保存照片.."];
    //获取单张图片并上传
    dispatch_group_t group = dispatch_group_create();
    __block BOOL isUploadFail = NO;
    for (KV2CameraAngleModel * angle in cellListData) {
        if (angle.normalImageUrl.length == 0 && angle.normalImage) {
            //取出图片
            UIImage *image = angle.normalImage;
            //上传图片
            dispatch_group_enter(group);
            
            [AppHttpClient userModule_uploadImage:image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
                if (success) {
                    NSLog(@"----->上传成功");
                    angle.normalImageUrl = imageUrl;
                    //上传合并图片
                    [AppHttpClient userModule_uploadImage:angle.syncImage completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
                        if (success) {
                            NSLog(@"----->上传成功");
                            angle.syncImageUrl = imageUrl;
                        }
                        
                        dispatch_group_leave(group);
                    }];
                }else{

                    isUploadFail = YES;
                    dispatch_group_leave(group);
                }
                
            }];
        }
    }
    
    WEAKSELF
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        progressHUD.hidden = YES;
        
        if (isUploadFail) {
            [KLProgressHUD showErrorHUDWithMessage:@"保存失败,请重新保存"];
            return ;
        }
        
        NSMutableArray <NSMutableDictionary *>*arrayM = [NSMutableArray array];
        KV2CameraAngleModel * lastAngle;
        for (KV2CameraAngleModel *angle in cellListData) {
            
            if ([angle.name isEqualToString:@"添加自定义"]) {
                break;
            }
            
            KV2CameraAngleModel * nowAngle = [[KV2CameraAngleModel alloc]init];
            nowAngle.normalImageUrl = angle.normalImageUrl;
            nowAngle.id = angle.id;
            nowAngle.syncImageUrl = angle.syncImageUrl;
            nowAngle.sort = angle.sort;
            nowAngle.isOneself = angle.isOneself;
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:nowAngle.normalImageUrl.length>0?nowAngle.normalImageUrl:@"" forKey:@"imageUrl"];
            [dict setValue:nowAngle.id.length>0?nowAngle.id:@"" forKey:@"templeId"];
            
            [dict setValue:nowAngle.syncImageUrl.length>0?nowAngle.syncImageUrl:@"" forKey:@"synthesisImageUrl"];
            
            if (nowAngle.sort.length == 0) {
                nowAngle.isOneself = @"1";
                if (lastAngle) {
                    nowAngle.sort = @(lastAngle.sort.intValue+1).stringValue;
                }else{
                    nowAngle.sort = @"1";
                }
            }else{
                nowAngle.isOneself = @"0";

            }
            [dict setValue:nowAngle.isOneself forKey:@"isOneself"];

            [dict setValue:nowAngle.sort forKey:@"sort"];
            
            [arrayM addObject:dict];
            lastAngle = nowAngle;

        }
        
        NSError *error;
        NSData *date = [NSJSONSerialization dataWithJSONObject:arrayM options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
            NSLog(@"转换error：%@", error);
        }
        NSString *jsonStr = [[NSString alloc] initWithData:date encoding:NSASCIIStringEncoding];

        weakSelf.createModel.photographUserAngleJson = jsonStr;
        
        //跳转到下一级
        [weakSelf nextAction];
    });
}



#pragma mark ----action----
-(void)nextAction{
    
    
    self.createModel.cateId = self.cateModel.id;
    self.createModel.subCateId = self.cateSubModel.id;
    self.createModel.partyId = self.partyId;

    XMTypeListViewController * vc = [[XMTypeListViewController alloc]init];
    vc.createModel = self.createModel;
    vc.timeStr = self.cateModel.name;
    vc.type = 1; 
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ----tableView----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        
        if (self.normalModel.cateViews.count%3) {
            return (self.normalModel.cateViews.count/3+1)*60;
        }else{
            return 60*(self.normalModel.cateViews.count/3);
        }
        
    }else if(indexPath.section == 1){
        if (self.normalModel.cateViewsSub.count%3) {
            return (self.normalModel.cateViewsSub.count/3+1)*60;
        }else{
            return 60*(self.normalModel.cateViewsSub.count/3);
        }
        
        
    }else{
        
        if ((self.normalModel.photoAngleTemplateViews.count+1)%2) {
            return  KRealValue(200)*((self.normalModel.photoAngleTemplateViews.count+1)/2+1);
        }else{
            return  KRealValue(200)*((self.normalModel.photoAngleTemplateViews.count+1)/2);

        }

    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 30.f;
    }else{
        return 0;
    }
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = kWhiteColor;
    
    UILabel * titleLabel = [[UILabel alloc]init];
    titleLabel.font = kFont(14);
    titleLabel.textColor = kTextGrayColor;
    [view addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
    }];
    
    if (section == 0) {
        titleLabel.text = @"时间节点";

    }else{
        titleLabel.text = @"拍摄部位";

    }
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 10.f;
    }else{
        return 0;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = kBgColor;
    return view;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 || indexPath.section == 1) {
        XMCameraTimeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMCameraTimeTableViewCell className]];
        if (!cell) {
            cell = [[XMCameraTimeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMCameraTimeTableViewCell className]];
        }
        
        //一级分类
        if (indexPath.section == 0) {
            cell.type = 1;
            cell.listArr = self.normalModel.cateViews;
            
            
            MJWeakSelf
            [cell setClickItemBlock:^(KV2GetCameraAngleCateModel * model) {
                weakSelf.cateModel = model;
                [weakSelf getAngleList];
            }];
            //二级分类
        }else{
            cell.type = 2;
            cell.listArr = self.normalModel.cateViewsSub;
            

            
            MJWeakSelf
            [cell setClickItemBlock:^(KV2GetCameraAngleCateModel * model) {
                weakSelf.cateSubModel = model;
                [weakSelf getAngleList];
            }];
        }
        
        return cell;
        
    }else{
        
        XMCameraAngleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMCameraAngleTableViewCell className]];
        if (!cell) {
            cell = [[XMCameraAngleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMCameraAngleTableViewCell className]];
        }
        
        cell.data = self.normalModel.photoAngleTemplateViews;
        MJWeakSelf
        [cell setAddCellBlock:^{
            [weakSelf.tableView reloadData];
            [weakSelf.tableView scrollToBottom];
        }];
        
        return cell;
    }
    
}


#pragma mark ----getting&setting----
-(UIButton *)nextBtn{
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextBtn setBackgroundColor:kMainBlueColor];
        [_nextBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(checkImage) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_nextBtn];
    }
    return _nextBtn;
    
}


-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}



-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache]clearMemory];
}

@end
